<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\RestoreAct;
use App\Admin\Extensions\Tools\Trashed;
use App\Admin\Extensions\Tools\BatchRestore;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use App\Models\Xapp;
use Encore\Admin\Facades\Admin;

class AppController extends AdminController
{
	public $title = '应用管理';

	
    /**
     * Get content title.
     *
     * @return string
     */
    public function title()
    {
        return $this->title;
    }


    /**
     * Edit interface.
     *
     * @param mixed   $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {		
		return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
			->breadcrumb(['text' => '应用管理','url'=>'/app'],['text' => '编辑'])
            ->body($this->form()->edit($id));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {  
		$trashed=request('trashed',0);
		$grid = new Grid(new Xapp());
		
		$grid->model()->orderBy('order','asc');
		$grid ->disablePagination();

		$grid->setActionClass('\App\Admin\Extensions\Tools\IdActions');

		$grid->tools->disableBatchActions(true);
		$grid->tools(function ($tools) {
            $tools->append(new Trashed());
        });


		$grid->column('id', 'ID');
		if($trashed){
			$grid->column('title', '标题');
			$grid->column('name', '标识')->display(function($name){
				if($this->parent_id){
					return '('.$this->parent_id.') '.$name;
				}else{
					return $name;
				}
			});		
		}else{
			$grid->column('title', '标题')->display(function($title) {
				$pre = '';
				if($this->parent_id){				
					$pre = ' └─ ';
				}
				return $pre.$title;
			});
			$grid->column('name', '标识')->display(function($name) {
				$pre = '';
				if($this->parent_id){				
					$pre = '&nbsp;&nbsp;└─&nbsp;&nbsp;';
				}
				return $pre."<a href='".admin_base_path('xapps/'.$name)."'>{$name}</a>";
			});	
		}
		$grid->column('table', '表名');
		if(empty($trashed)){
			$grid->column('_manager', '管理')->display(function () {
					$re = '';
					$opens = $this->sets['base'] ?? [];
					foreach(config('xapp.xappset') as $name=>$xapp){
						if(!empty($xapp['manager']) && !empty($opens[$name])) {
							$re.="<a href='".admin_base_path('app/'.$this->id.'/'.$name)."'>".$xapp['title']."管理</a><br />";
						}
					}
					return $re;
				});
			$grid->column('_set', '设置')->display(function (){
					return "<a href='".route('admin.app.set',['id'=>$this->id])."')'>设置</a>";
				});		
			
		}else{
			$grid->model()->onlyTrashed();
			$grid->actions(function ($actions) {
				$actions->append(new RestoreAct($actions->getKey())); 
			});
		}
        return $grid;
    }

   

	/**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
			

		$tables = config('xapp.table');
		$tablesel = empty($tables) ? [] : array_keys($tables);
		
		$tablesel = array_combine($tablesel,$tablesel);
		$form = new Form(new Xapp());
        $form->display('id', 'ID');

		
		
		$form->select('parent_id', '依赖')->options(function(){
				if(empty($this->id)){
					$rs = \App\Models\Xapp::where('parent_id',0)->pluck('title','id')->toArray();
					$rs[0] = '无';		
				}else{
					$child = \App\Models\Xapp::where('parent_id',$this->id)->withTrashed()->first();
					if(empty($child)){
						$rs = \App\Models\Xapp::where('parent_id',0)->where('id','!=',$this->id)->pluck('title','id')->toArray();
					}
					$rs[0] = '无';
				}
				return $rs;
			});
 		$form->text('title', '标题')->help('简单描述应用')->rules('required');
		$form->text('name', '标识')
			->creationRules('required|unique:xapps,name|regex:/^[a-z][a-z_]+$/',['regex' => '名称必须是英文开头且只包含小写字母、下划线'])
			->updateRules('required|unique:xapps,name,{{id}}|regex:/^[a-z][a-z_]+$/',['regex' => '名称必须是英文开头且只包含小写字母、下划线']);
		$form->select('table', '表名')
			->options($tablesel)
			->rules('required');

		$form->embeds('ctrl','控制器设置', function ($form) {
			$form->text('admin','后台')->help('一般不填,默认根据表名在config/xapp.php中设置');
			$form->text('web','前台')->help('一般不填,默认根据表名在config/xapp.php中设置');
			$form->text('api','Api')->help('一般不填,默认根据表名在config/xapp.php中设置');
		});
        return $form;

    }

    public function show($id, Content $content)
    {
		return $content->header('应用记录')
			->breadcrumb(
					['text' => '应用管理', 'url' => 'app'],
					['text' => '应用记录']
				)
            ->description('详情')
            ->body(Admin::show(Xapp::withTrashed()->findOrFail($id), function (Show $show) {
                $show->id('ID');
				$show->name('名称');
                $show->title('标题');
                $show->table('表');
				$show->sets('设置')->unescape()->as(function ($sets) {
						if(empty($sets)) return '';
						$re = '';
						foreach($sets as $name => $v ){
							$re .= $name.'设置:<pre><code>'.json_encode($v,JSON_UNESCAPED_UNICODE).'</code></pre>'; 
						}
						return $re;
					});
        		}));
    }


    public function restore(Request $request)
    {
        //只允许单记录处理;
		$id = $request->get('ids');		
		$rs = Xapp::onlyTrashed()->findOrFail($id);
		if($rs->parent_id){
			$parent = Xapp::withTrashed()->find($rs->parent_id);
			if(empty($parent)){
				$rs->parent_id = 0;
				$rs->deleted_at = Null;
				$rs->save();
			}else{
				admin_error('error','必须先恢复所依赖的应用');
			}
		}else{
		    Xapp::onlyTrashed()->find($id)->restore();
		}
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {        
		//只允许单记录处理;
		$childs = Xapp::where('parent_id',$id)->get()->toArray(); 
		if(!empty($childs)){
			$id = arr2str(array_column($childs,'id')).','.$id;
		}		
		return $this->form()->destroy($id);
    }

    /**
     * Make a set form.
     *
     * @return Form
     */
    public function set(Content $content,$id)
    {
		$active = request('active','base');
		$rs = Xapp::findOrFail($id);
		//$table = Schema::getColumnListing($rs->table);
		$sets['base'] = \App\Admin\Forms\Xappsets\Base::class;
		$opens = $rs->sets['base']??[];
		if(!empty(config('xapp.table.'.$rs['table'].'.set'))){
			$sets['table'] = config('xapp.table.'.$rs['table'].'.set');
		}
		foreach(config('xapp.xappset') as $k=>$v){
			if(!empty($opens[$k]) && !empty($v['set']) ){
				$sets[$k] = $v['set'];
			}
		}
		
		return $content
            ->title('应用设置')
			->breadcrumb(['text' => '应用管理','url'=>'app'],['text' => '应用设置'])
            ->body(Tab::forms($sets));
    }
}
